<script lang="ts" setup>
import type { ItemRecpt } from '#/api';

import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, InputSearch } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenForm } from '#/adapter/form';
import { addItemRecpt, updateItemRecpt } from '#/api';
import SearchVendorModal from '#/utils/view/vendor/searchvendormodal.vue';

import { useSchema } from './data';
import SearchItemRecptModal from './modules/arrivalnoticemodal.vue';
import MaterialTableGrid from './modules/materialtable.vue';

const emit = defineEmits(['success']);
const formData = ref<ItemRecpt.Row>();
const title = ref<string>();
const showConfrimBtn = ref(true);
const vendorName = ref<string>();
const noticeCode = ref<string>();
// 是否显示物料表格
const showMaterialTable = ref(false);
const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid grid-cols-12',
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: useSchema(),
  showDefaultActions: false,
});

const getTitle = computed(() => {
  if (formData.value?.attr1 === '1') return '查看入库单信息';
  return formData.value?.attr1 === '2' ? '编辑入库单信息' : '新增入库单信息';
});
watch(getTitle, (newTitle) => {
  title.value = newTitle;
});
const [Modal, modalApi] = useVbenModal({
  class: 'w-[800px]',
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await formApi.getValues().then((res) => {
        data = res;
      });
      try {
        await (formData.value?.recptId
          ? updateItemRecpt(data!)
          : addItemRecpt(data!));
        modalApi.close();
        emit('success');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<ItemRecpt.Row>();
      if (data) {
        // 回显格式化日期
        data.recptDate = dayjs(data.recptDate) as any;
        formData.value = data;
        formApi.setValues(formData.value);
        vendorName.value = formData.value?.vendorName;
        noticeCode.value = formData.value?.noticeCode!;
        showMaterialTable.value = !!data.recptId;
        showConfrimBtn.value = formData.value?.attr1 !== '1';
        modalApi.setState({
          showConfirmButton: showConfrimBtn.value,
        });
      }
    }
  },
});
function resetForm() {
  formApi.resetForm();
  formApi.setValues({});
}

// 供应商搜索子弹框
const [VendorModal, vendorModalApi] = useVbenModal({
  connectedComponent: SearchVendorModal,
  // 确认关闭或取消子弹框后回显数据
  onClosed() {
    vendorName.value = vendorModalApi.getData().vendorName;
    formApi.setFieldValue('vendorId', vendorModalApi.getData().vendorId);
    formApi.setFieldValue('vendorName', vendorModalApi.getData().vendorName);
  },
});

// 到货通知单子弹框
const [ArrivalModal, arrivalModalApi] = useVbenModal({
  connectedComponent: SearchItemRecptModal,
  // 确认关闭或取消子弹框后回显数据
  onClosed() {
    noticeCode.value = arrivalModalApi.getData().noticeCode;
    formApi.setFieldValue('noticeCode', arrivalModalApi.getData().noticeCode);
    formApi.setFieldValue('poCode', arrivalModalApi.getData().poCode);
  },
});
// 点击提交更改单据状态
function changeStatus() {
  formApi.setFieldValue('status', 'APPROVED');
  modalApi.onConfirm();
}
</script>

<template>
  <Modal :title="getTitle" :show-confirm-button="false">
    <Form class="mx-4">
      <template #noticeCode>
        <InputSearch
          placeholder="请选择到货通知单"
          @search="arrivalModalApi.open()"
          v-model:value="noticeCode"
          readonly
        />
      </template>
      <template #vendorName>
        <InputSearch
          placeholder="请选择供应商"
          @search="vendorModalApi.open()"
          v-model:value="vendorName"
          readonly
        />
      </template>
    </Form>
    <div v-if="showMaterialTable">
      <MaterialTableGrid
        :id="formData?.recptId!"
        :status="formData?.status!"
        :attr1="formData?.attr1 as any"
      />
    </div>

    <template #prepend-footer>
      <div
        class="flex flex-auto justify-between"
        v-if="
          (showConfrimBtn && formData?.status === 'PREPARE') || !formData?.attr1
        "
      >
        <div>
          <Button type="primary" danger @click="resetForm"> 重置 </Button>
        </div>
        <div class="flex gap-2">
          <Button
            type="primary"
            class="bg-[#67c23a] hover:!bg-[#a3db87]"
            @click="modalApi.onConfirm"
          >
            保存
          </Button>
          <Button type="primary" @click="changeStatus" v-if="formData?.attr1">
            提交
          </Button>
        </div>
      </div>
    </template>
  </Modal>
  <VendorModal />
  <ArrivalModal />
</template>
